/*
 * Copyright (C) 2009 AnK Team
 *	 Andrey Korolev
 *	 Anna Krel
 *	 Anna Kapanina
 *	 
 *	 http://code.google.com/p/ankfood/	
 *    
     
 *    Licensed under the GNU General Public License, Version 2.0 (the "License");
 *
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *         http://www.gnu.org/licenses/gpl-2.0.html

 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,

 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package org.ank.food;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

public class MenuManager {
	
	protected final static int[] NOT_DESIRABLE_GROUPS = {19,21,22,25,35};
	protected final static String[] NOT_DESIRABLE_NAMES = {"alcohol"};
	public final static String QUOTAS_EXEEDED_STRING = "_1";
	public final static String QUOTAS_EXEEDED_PROT_STRING = "_2";
	public final static String QUOTAS_EXEEDED_FAT_STRING = "_3";
	public final static String QUOTAS_EXEEDED_CARBO_STRING = "_2";
	
    protected ContentValues values;
    protected Context context;
//	protected int currentProfileId;
    
	protected volatile static MenuManager instance;
	
	protected MenuManager(Context c) {
		this.values = new ContentValues();
		this.context = c;
	}
 
    public static MenuManager getInstance(Context c) {
        if (instance == null) {
            synchronized (MenuManager.class) {
                if (instance == null) {
                    instance = new MenuManager(c);
                    
                }
            }
        }
        return instance;
    }

    public void deleteProfile(int id){
    	context.getContentResolver().delete(MenuProvider.CONTENT_URI, 
    			MenuProvider.COLUMN_NAMES[MenuProvider.PROFILE_ID]+"="+String.valueOf(id), null);
    }
    
    protected boolean groupIsAcceptable(int group){
		int i;
		for (i = 0; i < NOT_DESIRABLE_GROUPS.length; i++)
			if ( group == NOT_DESIRABLE_GROUPS[i])
				return false;
		return true;
	}
    
    protected boolean productNameIsAcceptable(String name){
		int i;
		for (i = 0 ; i < NOT_DESIRABLE_NAMES.length; i++)
			if (name.toLowerCase().contains(NOT_DESIRABLE_NAMES[i]))
				return false;
		return true;
	}
    

    
//    public void saveNewMenuItem(int productId, String productName,
//    		String weightItemName, int weightItemAmount, float weightItemWeight){
//    	int currentProfileId = ProfileManager.getInstance(context).getCurrentProfileId();
//    	saveNewMenuItem(currentProfileId, productId, productName, weightItemName, 
//    			weightItemAmount, weightItemWeight);
//    	
//    }
//    
//    public void saveNewMenuItem(String[] productInfo, String weightItemName, 
//    		int weightItemAmount, float weightItemWeight){
//    	int currentProfileId = ProfileManager.getInstance(context).getCurrentProfileId();
//    	int productId = Integer.parseInt(productInfo[1]);
//    	saveNewMenuItem(currentProfileId, productId, productInfo[1], weightItemName, 
//    			weightItemAmount, weightItemWeight);
//    	
//    }
    
    public void saveNewMenuItem(int productId, int weightItemId, int weightItemAmount){
    	ProductDataManager pm = ProductDataManager.getInstance(context); 
    	int currentProfileId = ProfileManager.getInstance(context).getCurrentProfileId();
    	String productName = pm.getProductNameById(productId);
    	String weightItemName = pm.getWeightItemNameById(weightItemId);
    	float weightItemWeight = pm.getWeightItemWeightById(weightItemId);
    	
    	saveNewMenuItem(currentProfileId, productId, productName, weightItemId,
    			weightItemName,	weightItemAmount, weightItemWeight);
    }
    
    public void saveNewMenuItem(int profileId, int productId, String productName,
    		int weightItemId, String weightItemName, int weightItemAmount, float weightItemWeight){
    	values = new ContentValues();
    	values.put(MenuProvider.COLUMN_NAMES[MenuProvider.ID],
    			findMinFreeIndex());
    	values.put(MenuProvider.COLUMN_NAMES[MenuProvider.PRODUCT_ID],
        		productId );
    	values.put(MenuProvider.COLUMN_NAMES[MenuProvider.PROFILE_ID],
    			profileId );
    	values.put(MenuProvider.COLUMN_NAMES[MenuProvider.PRODUCT_NAME],
        		productName );
    	values.put(MenuProvider.COLUMN_NAMES[MenuProvider.WEIGHT_ITEM_ID],
        		weightItemId );
    	values.put(MenuProvider.COLUMN_NAMES[MenuProvider.WEIGHT_ITEM_NAME],
        		weightItemName );
    	values.put(MenuProvider.COLUMN_NAMES[MenuProvider.WEIGHT_ITEM_AMOUNT],
        		weightItemAmount );
    	values.put(MenuProvider.COLUMN_NAMES[MenuProvider.WEIGHT_ITEM_WEIGHT],
        		weightItemWeight );
//    	////Log.v("saveNewEaten", "productinfo is "+productInfo[0]+", "+productInfo[1]);
//    	////Log.v("saveNewEaten", "values are "+values);
    	context.getContentResolver().insert(MenuProvider.CONTENT_URI, values);
    }
    
    public void updateMenuItem(int menuItemId, int weightItemId, int weightItemAmount){
    	ProductDataManager pm = ProductDataManager.getInstance(context); 
    	String weightItemName = pm.getWeightItemNameById(weightItemId);
    	float weightItemWeight = pm.getWeightItemWeightById(weightItemId);
    	values = new ContentValues();
    	values.put(MenuProvider.COLUMN_NAMES[MenuProvider.WEIGHT_ITEM_NAME],
        		weightItemName );
    	values.put(MenuProvider.COLUMN_NAMES[MenuProvider.WEIGHT_ITEM_AMOUNT],
        		weightItemAmount );
    	values.put(MenuProvider.COLUMN_NAMES[MenuProvider.WEIGHT_ITEM_WEIGHT],
        		weightItemWeight );
    	context.getContentResolver().update(MenuProvider.CONTENT_URI, values, 
    			MenuProvider.COLUMN_NAMES[MenuProvider.ID]+" = "+menuItemId, null);
    }
    
    public void deleteMenuItem(int id){
    	context.getContentResolver().delete(MenuProvider.CONTENT_URI, 
    			MenuProvider.COLUMN_NAMES[MenuProvider.ID] + " = "+String.valueOf(id), 
    			null);
    }
    
    public void clearMenu(){
    	context.getContentResolver().delete(MenuProvider.CONTENT_URI, 
    			MenuProvider.COLUMN_NAMES[MenuProvider.PROFILE_ID] + " = "+String.valueOf(
						ProfileManager.getInstance(context).getCurrentProfileId()), 
    			null);
    }
    
     protected int getMenuProtEnergy(){
    	int result = 0, prodId;
    	Cursor eatenCursor = getMenuCursor();
    	eatenCursor.moveToFirst();
    	int legth = eatenCursor.getCount();
    	for(int i = 0; i < legth; i++){
    		eatenCursor.moveToPosition(i);
    		prodId = eatenCursor.getInt(2);
    		
    		result += ProductDataManager.getInstance(context).getProductProtEnergy(prodId)*
    			eatenCursor.getInt(3)*Math.round(eatenCursor.getFloat(5))/
    			ProductDataManager.STANDARD_WEIGHT; 
    	}
    	eatenCursor.close();
    	return result;
    }
    protected int getMenuFatEnergy(){
    	int result = 0, prodId;
    	Cursor eatenCursor = getMenuCursor();
    	eatenCursor.moveToFirst();
    	int legth = eatenCursor.getCount();
    	for(int i = 0; i < legth; i++){
    		eatenCursor.moveToPosition(i);
    		prodId = eatenCursor.getInt(2);
    		result += ProductDataManager.getInstance(context).getProductFatEnergy(prodId)*
			eatenCursor.getInt(3)*Math.round(eatenCursor.getFloat(5))/
			ProductDataManager.STANDARD_WEIGHT;
    	}
    	eatenCursor.close();
    	return result;
    }
    protected int getMenuCarboEnergy(){
    	int result = 0, prodId;
    	Cursor eatenCursor = getMenuCursor();
    	eatenCursor.moveToFirst();
    	int legth = eatenCursor.getCount();
    	for(int i = 0; i < legth; i++){
    		eatenCursor.moveToPosition(i);
    		prodId = eatenCursor.getInt(2);
    		result += ProductDataManager.getInstance(context).getProductCarboEnergy(prodId)*
			eatenCursor.getInt(3)*Math.round(eatenCursor.getFloat(5))/
			ProductDataManager.STANDARD_WEIGHT;
    	}
    	eatenCursor.close();
    	return result;
    }
	
	public Cursor getMenuCursor(){
		String[] returnFields = {
			MenuProvider.COLUMN_NAMES[MenuProvider.PRODUCT_NAME],
			MenuProvider.COLUMN_NAMES[MenuProvider.ID],
			MenuProvider.COLUMN_NAMES[MenuProvider.PRODUCT_ID],
			MenuProvider.COLUMN_NAMES[MenuProvider.WEIGHT_ITEM_AMOUNT],
			MenuProvider.COLUMN_NAMES[MenuProvider.WEIGHT_ITEM_NAME],
			MenuProvider.COLUMN_NAMES[MenuProvider.WEIGHT_ITEM_WEIGHT]
		};
//		////Log.v("getEaten", "cur_profile_id = "+String.valueOf(
//				ProfileManager.getInstance(context).getCurrentProfileId()));
		return context.getContentResolver().query(MenuProvider.CONTENT_URI, 
				returnFields, 
				MenuProvider.COLUMN_NAMES[MenuProvider.PROFILE_ID]+" = "+String.valueOf(
						ProfileManager.getInstance(context).getCurrentProfileId()),
				null, null);
	}
	

	
	public boolean makeAndSaveSingleAdvice(int groupId){
//		int protQuota, fatQuota, carboQuota;
//		String[] productInfo;
//
//		//get quotas from profile info
//		ProfileManager prfM = ProfileManager.getInstance(context); 
//		ProductDataManager prdM = ProductDataManager.getInstance(context);
//		protQuota = prfM.getProtQuota();
//		fatQuota = prfM.getFatQuota();
//		carboQuota = prfM.getCarboQuota();
////		////Log.v("getAdvice","quotas from profileM = "+protQuota+" "+fatQuota+" "+carboQuota);
//		
//		/*
//		subtract amounts taken from EatenToday info
//
//		 */
//		protQuota -= getEatenProtEnergy();
//		fatQuota -= getEatenFatEnergy();
//		carboQuota -= getEatenCarboEnergy();
//	
//		prdM.setProtQuota(protQuota);
//		prdM.setFatQuota(fatQuota);
//		prdM.setCarboQuota(carboQuota);
//
//		boolean nameIsAcceptable = false;
//		productInfo = null;
//		while( !nameIsAcceptable ){
//			if ( (productInfo = prdM.getSuitableProductNameAndId(groupId)) != null ){
//				nameIsAcceptable = productNameIsAcceptable(productInfo[1]);
//			}else{
//				break;
//			}
//		}
//		if (productInfo != null){
////			////Log.v("advice","saving new advice: "+productInfo[0]);
//			saveNewEaten(productInfo);
//			return true;
//		}
////		////Log.v("advice","saving new advice");
//		return false;	
		
			ProductDataManager prdM = ProductDataManager.getInstance(context);
			Cursor c = prdM.getProductsByGroup(groupId);
			int pos, prodId, counter = 0;
			while(  counter  <  (c.getCount())  ){
				pos = (int)Math.round( Math.floor(    Math.random() * c.getCount()   ) );
//				pos = counter;
//				Log.v("saveadvise","c.getCount = "+c.getCount());
//				Log.v("saveadvise","pos = "+pos);
				c.moveToPosition(pos);
				prodId = c.getInt(1);
//				Log.v("saveadvise","prodID = "+prodId);
				int[] prodInfo;
				
				if ( ( prodInfo = prdM.getRecommendedWeightAsIntArr(prodId) )  != null){
					c.close();
					saveNewMenuItem(prodId, prodInfo[0], 1);
					return true;
				}
				counter++;
			}
			c.close();
			return false;
	}
    
	
    private int findMinFreeIndex(){
    	int length, curIndex=0, prevIndex;
    	Cursor c = context.getContentResolver().query(MenuProvider.CONTENT_URI, 
    			new String[]{ MenuProvider.COLUMN_NAMES[MenuProvider.ID] },
    			null,null, MenuProvider.COLUMN_NAMES[MenuProvider.ID]+" asc" );
    	
    	//if there are no entries in database, return 0
    	if (  ( length = c.getCount() ) == 0  ){
    		c.close();
    		return 0;
    	}
    	
    	//check index at first position of the cursor. If this index is not 0,
    	//then 0 is free, so return 0
    	c.moveToFirst();
    	if ( (prevIndex = c.getInt(0)) != 0){
    		c.close();
    		return 0;
    	}
    		
    	//so, 0 isn't free. Then we'll check every next position, and if
    	//its index differs from previous at more than 1, we will use the
    	//missing index
    	for(int i = 1; i < length ; i++ ){
    		c.moveToPosition(i);
    		if ( ( curIndex = c.getInt(0) ) != prevIndex+1 )
    			return prevIndex+1;
    		prevIndex = curIndex; 
    	}
    	
    	//if we reached the last position and found no missing index,
    	//return the last+1;
    	return curIndex+1;
    	
    }
    
    public int getMenuItemAmount(int id){
    	String[] returnFields = {
    			MenuProvider.COLUMN_NAMES[MenuProvider.WEIGHT_ITEM_AMOUNT]
    		};
    		Cursor c = context.getContentResolver().query(MenuProvider.CONTENT_URI, 
    				returnFields, 
    				MenuProvider.COLUMN_NAMES[MenuProvider.ID]+" = "+id,
    				null, null);
    		c.moveToFirst();
     		int a = c.getInt(0); 
    		c.close();
    		return a;
    }
    
    public String getMenuItemWeightName(int id){
    	String[] returnFields = {
    			MenuProvider.COLUMN_NAMES[MenuProvider.WEIGHT_ITEM_NAME]
    		};
    		Cursor c = context.getContentResolver().query(MenuProvider.CONTENT_URI, 
    				returnFields, 
    				MenuProvider.COLUMN_NAMES[MenuProvider.ID]+" = "+id,
    				null, null);
    		c.moveToFirst();
     		String s = c.getString(0); 
    		c.close();
    		return s;
    }
    
    public int getMenuItemWeightId(int itemId){
    	String[] returnFields = {
    			MenuProvider.COLUMN_NAMES[MenuProvider.WEIGHT_ITEM_ID]
    		};
    		Cursor c = context.getContentResolver().query(MenuProvider.CONTENT_URI, 
    				returnFields, 
    				MenuProvider.COLUMN_NAMES[MenuProvider.ID]+" = "+itemId,
    				null, null);
    		c.moveToFirst();
     		int a = c.getInt(0); 
    		c.close();
    		return a;
    }
    
    public String getMenuItemProductName(int id){
    	String[] returnFields = {
    			MenuProvider.COLUMN_NAMES[MenuProvider.PRODUCT_NAME]
    		};
    		Cursor c = context.getContentResolver().query(MenuProvider.CONTENT_URI, 
    				returnFields, 
    				MenuProvider.COLUMN_NAMES[MenuProvider.ID]+" = "+id,
    				null, null);
    		c.moveToFirst();
     		String s = c.getString(0); 
    		c.close();
    		return s;
    }
    
    public int getMenuItemProductId(int itemId){
    	String[] returnFields = {
    			MenuProvider.COLUMN_NAMES[MenuProvider.PRODUCT_ID]
    		};
    		Cursor c = context.getContentResolver().query(MenuProvider.CONTENT_URI, 
    				returnFields, 
    				MenuProvider.COLUMN_NAMES[MenuProvider.ID]+" = "+itemId,
    				null, null);
    		c.moveToFirst();
     		int a = c.getInt(0); 
    		c.close();
    		return a;
    }
//    public boolean menuIsEmpty(){
//    	Cursor c = context.getContentResolver().query(MenuProvider.CONTENT_URI, 
//    			MenuProvider.COLUMN_NAMES[MenuProvider.ID], 
//				MenuProvider.COLUMN_NAMES[MenuProvider.ID]+" = "+current,
//				null, null);
//		c.moveToFirst();
// 		String s = c.getString(0); 
//		c.close();
//		return s;
//    	
//    }
    
    
    
    
    
}
